// 导入模块
import Vue from 'vue'
import axios from 'axios'
import { SERVER_BASE_URL, SERVER_CPT_URL } from './config'
import router from '@/router'
import iView, { Notice } from 'iview'
import qs from 'qs'
import store from '@/store'
import { getStore, setStore, Decrypt, Encrypt, inputString } from '@/common/utils'
Vue.use(iView)
// 设置用户信息action
/* const setUserInfo = function (user) {
 //store.dispatch(SET_USER_INFO, user)
 }; */

// 加密后端请求方法
export function fetch(options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: SERVER_BASE_URL,
      timeout: 5000,
      headers: {}
    })


    if (!getStore('token')) {
      router.replace({ name: "login" })
      return
    }
    
    // 加密数据  
    let tsu = {
      tdata: Encrypt(options.params, getStore('token').substr(5, 16))
    }
    console.log("qingqiu:",options.params,tsu.tdata)
   
    options.data = qs.stringify(tsu)
    console.log("options.data:",options.data)
    if(options.params){
      let ss=Decrypt(tsu.tdata,  getStore('token').substr(5, 16))
      console.log("ss:",ss)
    }

    options.params = {}
    // http request 拦截器
    instance.interceptors.request.use(
      config => {
        iView.LoadingBar.start()
        config.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
        // 添加token       
        if (getStore('token')) {
          config.headers.Authorization = getStore('token')
        }
        return config
      },
      err => {
        iView.LoadingBar.error()
        return Promise.reject(err)
      })

    // http response 拦截器
    instance.interceptors.response.use(
      response => {
        iView.LoadingBar.finish()
        // 数据解密        
        if (response.data.jdata) {
          let aeskey = getStore('token').substr(5, 16)
          let ciphertext = response.data.jdata
          let tsu = Decrypt(ciphertext, aeskey)
          store.commit('SET_TOKEN', response.data.token)
          response.data.Data = tsu
        }
        return response
      },
      error => {
        iView.LoadingBar.error()
        if (error) {
          // console.log(error)
          // switch (error.response.status) {
          // case 401:
          // 返回 401 清除token信息并跳转到登录页面
          store.commit('LOGOUT')
          router.replace({
            path: 'login',
            query: { redirect: router.currentRoute.fullPath }
          })
          // }
        }
        return Promise.reject(error) // 返回接口返回的错误信息
      })

    // 请求处理
    instance(options)
      .then((res) => {
        // 请求成功时,根据业务判断状态
        if (res.data.code === 0) {
          // console.log(res)
          resolve(res.data)
          return false
        } else {
          //  setUserInfo(null)
          Notice.error({
            title: '出错了！',
            desc: '错误原因 ' + JSON.stringify(res.data.message),
            duration: 5
          })
          if (res.data.status === 401) {
            router.replace({ name: "login" })
          }

        }
      })
      .catch((error) => {
        // 请求失败时,根据业务判断状态
        Notice.error({
          title: '服务出错了！',
          desc: '服务无响应，请联系系统管理员 ',
          duration: 5
        })
        reject(error)
        router.replace({ name: "login" })
      })
  })
}

// 非加密后端数据请求
export function fetchCPT(options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: SERVER_CPT_URL,
      timeout: 5000,
      headers: {}
    })
    // http request 拦截器
    instance.interceptors.request.use(
      config => {
        iView.LoadingBar.start()
        config.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
        // config.headers.Authorization = 'token'
        return config
      },
      err => {
        iView.LoadingBar.error()
        return Promise.reject(err)
      })

    // http response 拦截器
    instance.interceptors.response.use(
      response => {
        iView.LoadingBar.finish()
        return response
      },
      error => {
        iView.LoadingBar.error()
        console.log(error)
        store.commit('LOGOUT')
        router.replace({
          path: 'login',
          query: { redirect: router.currentRoute.fullPath }
        })
        return Promise.reject(error)

      })

    // 请求处理
    instance(options)
      .then((res) => {
        // 请求成功时,根据业务判断状态
        console.log(res)
        if (res.data.code === 0) {
          resolve(res.data)
          return false
        } else {
          //  setUserInfo(null)
          Notice.error({
            title: '数据出错了！',
            desc: '错误原因 ' + JSON.stringify(res.data.message),
            duration: 5
          })
          if (res.data.status === 401) {
            router.replace({ name: "login" })
          }

        }
      })
      .catch((error) => {
        // 请求失败时,根据业务判断状态
        console.log(error)
        Notice.error({
          title: '服务出错了！',
          desc: '服务无响应，请联系系统管理员 ',
          duration: 5
        })
        reject(error)
      })
  })
}
